package com.zsguan.z.zhttp4andr;

import android.content.Context;

import com.zsguan.z.slogger4andr.ZLogger;
import com.zsguan.z.zhttp4andr.exception.ZException;
import com.zsguan.z.zhttp4andr.exception.ZHttpException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Map;

/**
 * Created by chshqiang on 15-9-12.
 * Http Manager
 */
class HttpManager {

    private static SSLSocketFactory sSSLSocketFactory;


    public static String openUrl(Context context, String url, Map<String, String> params) throws ZException {
        ZParameters bplayParameters = new ZParameters();
        bplayParameters.setParams(params);

        HttpResponse response = requestHttpExecute(context, url, "POST", bplayParameters);
        return readRsponse(response);
    }

    private static HttpResponse requestHttpExecute(Context context, String url, String method, ZParameters params) {
        HttpClient client = null;
        ByteArrayOutputStream baos = null;
        HttpResponse response = null;

        try {
            client = getNewHttpClient(context);

            HttpUriRequest e = null;
            String result;
            if (method.equals("GET")) {
                url = url + "?" + params.encodeUrl();
                e = new HttpGet(url);
            } else if (!method.equals("POST")) {
                if (method.equals("DELETE")) {
                    e = new HttpDelete(url);
                }
            } else {
                HttpPost status = new HttpPost(url);
                e = status;
                baos = new ByteArrayOutputStream();

                status.setHeader("Content-Type", "application/x-www-form-urlencoded");
                status.setHeader("Charset", "UTF-8");

                result = params.encodeUrl();
                baos.write(result.getBytes("UTF-8"));

                status.setEntity(new ByteArrayEntity(baos.toByteArray()));
            }

            response = client.execute(e);
            StatusLine status1 = response.getStatusLine();
            int statusCode1 = status1.getStatusCode();
            if (statusCode1 != 200) {
                result = readRsponse(response);
                throw new ZHttpException(result, statusCode1);
            }
        } catch (IOException var18) {
            throw new ZException(var18);
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException ignored) {

                }
            }

            shutdownHttpClient(client);
        }

        return response;
    }

    private static void shutdownHttpClient(HttpClient client) {
        if (client != null) {
            try {
                client.getConnectionManager().closeExpiredConnections();
            } catch (Exception ignored) {

            }
        }

    }

    private static HttpClient getNewHttpClient(Context context) {
        try {
            BasicHttpParams e = new BasicHttpParams();
            HttpProtocolParams.setVersion(e, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(e, "UTF-8");
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", getSSLSocketFactory(context), 443));
            ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(e, registry);
            HttpConnectionParams.setConnectionTimeout(e, 25000);
            HttpConnectionParams.setSoTimeout(e, 20000);
            return new DefaultHttpClient(ccm, e);
        } catch (Exception var4) {
            return new DefaultHttpClient();
        }
    }

    private static String readRsponse(HttpResponse response) throws ZException {
        if (response == null) {
            return null;
        } else {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = null;
            InputStreamReader in = null;
            BufferedReader br = null;
            StringBuilder result = new StringBuilder();

            try {
                inputStream = entity.getContent();

                in = new InputStreamReader(inputStream);
                br = new BufferedReader(in);
                String line;

                while ((line = br.readLine()) != null) {
                    result.append(line);
                }

                return result.toString();
            } catch (IOException var19) {
                throw new ZException(var19);
            } finally {
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException var18) {
                        var18.printStackTrace();
                    }
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException var18) {
                        var18.printStackTrace();
                    }
                }
            }
        }
    }

    private static SSLSocketFactory getSSLSocketFactory(Context context) {
        if (sSSLSocketFactory == null) {
            try {
                String e = KeyStore.getDefaultType();
                KeyStore keyStore = KeyStore.getInstance(e);
                keyStore.load(null, null);
                Certificate cnCertificate = getCertificate(context, "server.cer");
                keyStore.setCertificateEntry("bestv", cnCertificate);
                sSSLSocketFactory = new SSLSocketFactoryEx(keyStore);
                ZLogger.i("HttpManager: " + "getSSLSocketFactory noraml ");
            } catch (Exception var4) {
                var4.printStackTrace();
                sSSLSocketFactory = SSLSocketFactory.getSocketFactory();
                ZLogger.i("HttpManager: " + "getSSLSocketFactory error default ");
            }
        }

        return sSSLSocketFactory;
    }

    private static Certificate getCertificate(Context context, String name) throws CertificateException, IOException {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        InputStream certInput = HttpManager.class.getResourceAsStream(name);

        if (null == certInput) {
            certInput = context.getAssets().open(name);
        }

        Certificate certificate;
        try {
            certificate = cf.generateCertificate(certInput);
        } finally {
            certInput.close();

        }

        return certificate;
    }
}
